<?php

  class ListingInformationHelper extends AppHelper
  {
    var $helpers  = array("CustomFieldDisplay");
    private $dispalyedFieldsets = array();
    function showField($listing,$field)
    {
        $FieldPropertyObject = $this->getAttributes($listing);
        return $this->CustomFieldDisplay->showField($FieldPropertyObject,$field,$listing['Listing']);
    }
     function getDirectValue($listing,$field)
    {
        return $this->getAttributes($listing)->getShowValue($field,$listing['Listing']);
    }
    function showFieldsetGroup($listing,$groupName,$onceOnly = true,$restrict = true)
    {
      $FieldPropertyObject = $this->getAttributes($listing);
      $fieldsetInfo = $FieldPropertyObject->getFieldsetInfo($groupName);
      if(!$fieldsetInfo)
      {
        return null;
      }
      if($onceOnly && in_array($fieldsetInfo['id'],$this->dispalyedFieldsets))
      {
        return null;
      }
      $this->dispalyedFieldsets[] = $fieldsetInfo['id'];
      $fields = $fieldsetInfo['fields'];
      unset($fieldsetInfo['fields']);
      $render = true;
      if($restrict)
      {
        $filterFields = $this->filterDisplayFields($listing, $fields);
        if($this->allowFieldsetDisplay($listing, $fieldsetInfo['id']) == false)
        {
           if(count($filterFields) == 0)
           {
             $render = false;
           }else
           {
             $fields = $filterFields;
           }
        }else if($filterFields)
        {
          $fields = $filterFields;
        }
      }
      if($render && count($fields))
      {
        return $this->getView()->element("listing_fieldset",array("listing"=>$listing,"fieldset"=>$fieldsetInfo,'fields'=>$fields));
      }
      
    }
    function showCompareListingField($listing,$field)
    {
      $FieldPropertyObject = $this->getAttributes($listing);
      return $this->CustomFieldDisplay->showField($FieldPropertyObject,$field,$listing['Listing'],  CustomFieldDisplayHelper::TEMPLATE_SIMPLE,true);
    }
    /**
     *
     * @return Listing
     */
    protected function getListingModel()
    {
       if(!isset($this->ListingModel))
        {
           $this->ListingModel = cri("Listing");
        }
        return $this->ListingModel;
    }
    /**
     *
     * @param type $listing
     * @return ListingFieldProperties 
     */
    function getAttributes($listing)
    {
      return $this->getListingModel()->getAttributes($listing);
    }
    
    function allowFieldsetDisplay($listing,$fieldsetId)
    {
      $restrictions = $this->getListingFieldRestrictions($listing);
      $return = true;
      if(is_array($restrictions['fieldset']) && !in_array($fieldsetId,$restrictions['fieldset']))
      {
        //Check that fields of this fieldset are also not present.
        $fieldsetInfo = $this->getAttributes($listing)->getFieldsetInfo($fieldsetId);
        $fields = $this->filterDisplayFields($listing,$fieldsetInfo['fields']);
        if(!$fields)
        {
          $return = false;
        }
      }
      return $return;
    }
    
    function filterDisplayFields($listing,$fields)
    {
      $restrictions = $this->getListingFieldRestrictions($listing);
      if(is_array($restrictions['fields']))
      {
        $FieldPropertyObject = $this->getAttributes($listing);
        foreach($fields as $key => $field)
        {
          $customFieldId = $FieldPropertyObject->getPropertyValue($field, 'custom_field_id');
          if(!in_array($customFieldId,$restrictions['fields']))
          {
            unset($fields[$key]);
          }
        }
      }
      return $fields;
    }
    
    protected function getListingFieldRestrictions($listing)
    {
      $listingRestrictions = array("fields"=>false,'fieldset'=>false);
      if(AppUtility::allowPaidListing())
      {
          $EffectivePlan = cri("PaidListings.ListingPlan")->getEffectivePlan($listing['Listing']['id']);
          //checks is there is need to restrict custom fields
          if($EffectivePlan->restrictFields())
          {
              //restrict Fields;
              $showAllFields = false;
              $visibleFieldsetIds = $EffectivePlan->getFieldsets();
              $visibleFieldsIds = $EffectivePlan->getCustomFields();
              $listingRestrictions = array("fieldset"=>$visibleFieldsetIds,'fields'=>$visibleFieldsIds);
          }
      }
      return $listingRestrictions;
    }
    
    function showListingCategories($listing, $isadmin=false)
    {
      $categories = array($listing['ListCategory']['id'] => array('ListCategory'=>$listing['ListCategory']));
      if(cr('ListingConfig.allow_multiple_categories'))
      {
        $additionalCategories = cri("AdditionalCategory")->getAdditionalCategories($listing['Listing']['id']);
        $categories = am($additionalCategories,$categories);
      }
      $categoryHtmlArray = array();
      foreach($categories as $category)
      {
      	if($isadmin)
      	{
      		$categoryHtml = $this->Html->link($category['ListCategory']['name'],$category['ListCategory']['viewAdminUrl']);
      	}
      	else 
      	{
        	$categoryHtml = $this->Html->link($category['ListCategory']['name'],$category['ListCategory']['viewUrl']);
      	}
        $categoryHtml = "<span class=\"category_name\">$categoryHtml</span>";
        $categoryHtmlArray[$category['ListCategory']['id']] = $categoryHtml;
      }
      return implode("<span>, </span>",$categoryHtmlArray);
    }
    
    /**
     *
     * @param type $categoriesList
     * @param type $selectedCategories - list of selected categories
     * @param type $inForm : if true it will insert selected categories below the main select box
     * @return string 
     */
    function showCategorySelector($categoriesList,$data = array(),$inForm = false)
    {
        $selectedCategories = array();
        if(isset($data['AdditionalCategory']))
        {
            $selectedCategories = Set::extract($data['AdditionalCategory'],'{n}.list_category_id');
        }else if(isset($data['Listing']['additional_categories']))
        {
            $selectedCategories = Set::extract($data['Listing']['additional_categories'],'{n}.list_category_id');
            
        }
        if(!cr('ListingConfig.allow_multiple_categories'))
        {
            return "";
        }
        $this->initHelper("Html");
        $this->initHelper("Javascript");
        $this->initHelper("Form");
        $this->Html->addJUI();
        $this->Html->css("/css/jquery.multiselect.css",array(),null,false);
        $this->Javascript->link('/js/jquery.multiselect.min.js',false);
        $categoriesSelectBox = $this->Form->input("Listing.additional_categories",array('id'=>"MultipcategorySelector","options"=>$categoriesList,'empty'=>false,'multiple'=>true,'value'=>$selectedCategories,'type'=>"select"));
        $div = '<div style="width:200px" id="MultipcategorySelectorWrapper">'.$categoriesSelectBox.'</div>';
        $headerLabel = $this->Javascript->object(__("Select other related categories"));
        $js =<<< END
        (function(){
            \$("#MultipcategorySelector").css({width : "30%"}).multiselect({
                header : $headerLabel,
                close : function()
                {
                    setValues();
                }
            }).attr('disabled',true);
            \$("#MultipcategorySelector").bind("enableSelector",function(){
                $(this).attr('disabled',false);
                $(this).parent().show();
                setValues();
            });
             \$("#MultipcategorySelector").bind("disableSelector",function(){
                $(this).attr('disabled',false);
                $(this).parent().hide();
                formElement.html("");
            });
            var formElement = \$('<div></div>'); 
            function setValues()
            {
                formElement.html("");
                var i = 0;
                \$.each(\$("#MultipcategorySelector").val() || [],function(key,val){
                    var inputName = 'data[Listing][additional_categories]['+i+'][list_category_id]';
                    formElement.append($('<input />').attr('type','hidden').attr('name',inputName).val(val));
                    i++;
                });
                console.log(formElement);
            }
            \$("body").bind("listingFormLoaded",function(){
                    \$('#listingFrom').append(formElement);
                    setValues();
            });
            $(document).ready(function(){
                \$('#listingFrom').append(formElement);
                setValues();
            })
       })()
END;
        $this->Javascript->startup($js);    
        return $div;
    }
  }
?>